﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Core;
using Forums;
using Forums.Models;


namespace Forums.Controllers
{
    [Permission("Can Contribute Documents")]
    public class AdminController : Controller
    {
        //
        // GET: /Admin/

        [Permission("Can Modify Domain")]
        public ActionResult Index()
        {
            ForumEntities forum = new ForumEntities();
            Guid BUId = (Guid)Session["BusinessUnitId"];
            ViewBag.BusinessUnitId = BUId;
            ViewBag.ParentForumId = Guid.Empty;
            return View();
        }

        //
        // GET: /Admin/

        [Permission("Can Modify Domain")]
        public ActionResult ForumIndex(Guid Id)
        {
            ForumEntities forum = new ForumEntities();
            Guid BUId = (Guid)Session["BusinessUnitId"];
            ViewBag.BusinessUnitId = BUId;
            ViewBag.ParentForumId = Id;
            return View("Index");
        }

        // Return Count of documents if IsReturnDocCountRequest is true.
        // Return Documents processed in this partition even if they are 0, if the partition cannot be processed return -1
        [HttpPost]
        public JsonResult Reindex(int partition, bool IsReturnDocCountRequest)
        {
            int retval = 0;
            return Json(retval);
        }

        //
        // POST: /ForumList/

        [HttpPost]
        public JsonResult ForumList(FormCollection collection)
        {
            Models.ForumEntities fe = new ForumEntities();
            Guid BUId = new Guid(collection.GetValues("BusinessUnitId")[0].ToString());
            Guid ParentForumId = new Guid(collection.GetValues("ParentForumId")[0].ToString());
            int SkipRecs = int.Parse(collection.GetValues("iDisplayStart")[0].ToString());
            int TakeCount = int.Parse(collection.GetValues("iDisplayLength")[0].ToString());
            string strSearch = collection.GetValues("sSearch")[0].ToString();
            DataTableResponse r = new DataTableResponse();
            List<Models.Forum> forumlist = fe.Forums.Where(m => (m.BusinessUnitId == BUId && m.Parent == ParentForumId && m.Name.Contains(strSearch) && m.IsDroppedYN == "N")).OrderBy(m => m.CreateDT).Skip(SkipRecs).Take(TakeCount).ToList();
            r.sEcho = collection.GetValues("sEcho")[0].ToString();
            // This query is required because the earlier query returns results for only 1 page. 
            // It also needs to execute here and value cannot be cached because the # of rows may change as rows get inserted/deleted
            r.iTotalRecords = fe.Forums.Where(m => (m.BusinessUnitId == BUId && m.Name.Contains(strSearch) && m.IsDroppedYN == "N")).Count();
            r.iTotalDisplayRecords = r.iTotalRecords;
            foreach (Models.Forum forum in forumlist)
            {
                List<string> r1 = new List<string>();
                string forumid = forum.ForumId.ToString();
                string editurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"editlink\" title=\"{1}\" >Edit</a>", "Forums/Admin", "Edit", forumid);
                string detailsurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"detailslink\" title=\"{1}\" >Details</a>", "Forums/Admin", "Details", forumid);
                string deleteurl = String.Format("<a href=\"/{0}/{1}/{2}\" id=\"deletelink\" title=\"{1}\" >Delete</a>", "Forums/Admin", "Delete", forumid);
                string foldersurl = String.Format("<a href=\"/{0}/{1}/{2}\" >Folders</a>", "Forums/Admin", "ForumIndex", forumid);
                string postsurl = String.Format("<a href=\"/{0}/{1}/{2}\" >Posts</a>", "Forums/Admin", "Posts", forumid);
                r1.Add(editurl + detailsurl + deleteurl + foldersurl + postsurl);
                r1.Add(forum.Name);
                r1.Add(String.Format("{0:g}", forum.ModifiedDT));
                r1.Add(forum.ModifiedByName);
                r1.Add(forum.CreatedByName);
                r.aaData.Add(r1);
            }
            return Json(r);
        }

        //
        // GET: /Create/

        [Permission("Can Modify Domain")]
        public ActionResult Create(Guid Id)
        {
            Forums.Models.ForumCreate forum = new ForumCreate((Guid)Session["BusinessUnitId"],Id);
            return View(forum);
        }


        //
        // POST: /Create/

        [HttpPost]
        [Permission("Can Modify Domain")]
        public ActionResult Create(ForumCreate forum)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    forum.UserId = (Guid)Session["UserId"];
                    forum.UserFullName = Session["UserFullName"].ToString();
                    forum.DomainId = (Guid)Session["DomainId"];
                    string retval = forum.Save();
                    if(retval != "")
                        ModelState.AddModelError("",retval);
                    else
                        return RedirectToAction("ForumIndex", new { Id = forum.ParentForumId });
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", Tools.ExceptionMessage(e));
                }
            }
            return View(forum);
        }
    }
}
